/*
 * console.c
 *
 *  Created on: 15/10/2011
 *      Author: utn_so
 */

#include "console.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "structsFAT.h"
#include "functionsFAT.h"
#include "fuseLayer.h"
#include "basicFunctions.h"

const char * _FSINFO = "fsinfo";
const char * _FINFO = "finfo";

void Command_fsinfo()
{
	int32_t CantBusyClusters = 0,
			CantFreeClusters = 0;
	setCantFreeAndBusyClusters(&CantFreeClusters, &CantBusyClusters);
	printf("Cantidad de clusters ocupados: %d, cantidad de clusters libres: %d, tamaño de un sector: %d bytes, tamaño de un cluster: %d bytes, tamaño de la FAT %d kilobytes\n",
			CantBusyClusters,
			CantFreeClusters,
			getSizeOfSector(),
			getSizeOfCluster(),
			getSizeFileAllocationTable() / 1024);
}

void Command_finfo(char * aFilePath)
{
	CLUSTER clusterlist[20];
	CLUSTER AuxCluster;
	List_FILE_INFO ListFiles;
	FILE_INFO aFileInfo;
	int32_t CantClustersInFile = 0,
			i = 0;
	char * path;
	char * aFileName;

	List_FILE_INFO_Init(&ListFiles);

	path = ExtractFilePath(aFilePath);
	aFileName = ExtractFilename(aFilePath);

	getEntrysFromPath(path, &ListFiles);
	if (setFileInfoByFileName(&ListFiles, aFileName, &aFileInfo) == -1) {
		free(aFileName);
		free(path);
		List_FILE_INFO_Destroy(&ListFiles);
		printf("File not found\n");
		return;
	}

	AuxCluster = aFileInfo.firstCluster;

	if (AuxCluster != 0) { //Que el archivo tenga un cluster asociado
		while ((CantClustersInFile < 20) && (!EOC(AuxCluster))) {
			clusterlist[CantClustersInFile] = AuxCluster;
			CantClustersInFile++;
			AuxCluster = NextCluster(AuxCluster);
		}
	}

	printf("Clusters:\n");
	if (CantClustersInFile == 0) {
		printf("No hay clusters asociados al archivo.\n");
	}
	else {
		printf("%d", clusterlist[0]);
		for(i = 1; i < CantClustersInFile; i++)
			printf(", %d", clusterlist[i]);
		printf(".\n");
	}

	free(aFileName);
	free(path);
	List_FILE_INFO_Destroy(&ListFiles);
}

void Command_execute(char * command, char * aFilePath)
{
	if(strcmp(command, _FSINFO) == 0) {
		Command_fsinfo();
		return;
	}
	if(strcmp(command, _FINFO) == 0) {
		Command_finfo(aFilePath);
		return;
	}
}

int Console_Run()
{
	char command[30 + 1];
	char aFilePath[256 + 1];
	char line[300 + 1];
	memset(command, 0, 31);
	while (1) {
		memset(command, 0, 31);
		memset(aFilePath, 0, 257);
		fgets(line, 301, stdin);
		if (strpos(line, ' ') > 0) {
			strncpy(command, line, strpos(line, ' '));
			command[30] = '\0';
			strncpy(aFilePath, &line[strpos(line, ' ') + 1], strpos(line, '\n') - 1 - strpos(line, ' '));
			aFilePath[256] = '\0';
		}
		else {
			strncpy(command, line, strpos(line, '\n'));
			command[30] = '\0';
		}
		Command_execute(command, aFilePath);
	}

	return 0;
}
